const express = require('express');
const { sendVerificationCode, verifyCode } = require('../controllers/authController');
const { body, validationResult } = require('express-validator');
const router = express.Router();

/**
 * @swagger
 * /auth/send-code:
 *   post:
 *     summary: 发送验证码
 *     tags: [Auth]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               phoneNumber:
 *                 type: string
 *                 example: "13576276460"
 *     responses:
 *       200:
 *         description: 验证码已生成
 *       500:
 *         description: 服务器错误
 */
router.post('/send-code',
  [
    body('phoneNumber')
      .isString()
      .matches(/^1[3-9]\d{9}$/)
      .withMessage('手机号格式不正确')
  ],
  (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    next();
  },
  sendVerificationCode
);

/**
 * @swagger
 * /auth/verify-code:
 *   post:
 *     summary: 验证验证码
 *     tags: [Auth]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               phoneNumber:
 *                 type: string
 *                 example: "13576276460"
 *               code:
 *                 type: string
 *                 example: ""
 *     responses:
 *       200:
 *         description: 验证成功
 *       400:
 *         description: 验证码错误或已过期
 *       500:
 *         description: 服务器错误
 */
router.post('/verify-code',
  [
    body('phoneNumber')
      .isString()
      .matches(/^1[3-9]\d{9}$/)
      .withMessage('手机号格式不正确'),
    body('code')
      .isString()
      .isLength({ min: 4, max: 4 })
      .withMessage('验证码必须是4位数字')
  ],
  (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    next();
  },
  verifyCode
);

module.exports = router;
